/**
 *
 */
package org.rico.commons.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

/**
 *
 * @author rico 2016年5月20日
 *
 */
public class CustomExceptionResolver extends SimpleMappingExceptionResolver {
    // 默认系统exception 提示信息
    private static final String DEFAULT_EXCEPTION_MESSAGE = "系统繁忙";

    private String exceptionMessage = DEFAULT_EXCEPTION_MESSAGE;

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        if(this.isAjaxRequest(request)) {
            try {
                // ajax 请求
                //logger.error(ex.getMessage(), ex);

                PrintWriter writer = response.getWriter();
                if(ex instanceof BusinessException) {
                    writer.write(ex.getMessage());
                } else {
                    writer.write(DEFAULT_EXCEPTION_MESSAGE);
                }

                response.setStatus(500);
                writer.flush();

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            if(ex instanceof BusinessException) {

            } else {
                ex = new BusinessException(DEFAULT_EXCEPTION_MESSAGE, ex);
            }

            return super.doResolveException(request, response, handler, ex);
			
			/*// Expose ModelAndView for chosen error view.
			String viewName = determineViewName(ex, request);
			if (viewName != null) {
				// Apply HTTP status code for error views, if specified.
				// Only apply it if we're processing a top-level request.
				Integer statusCode = determineStatusCode(request, viewName);
				if (statusCode != null) {
					applyStatusCodeIfPossible(request, response, statusCode);
				}
				
				return getModelAndView(viewName, ex, request);
			} else {
				return null;
			}*/
        }

        return null;
    }

    /**
     * 判断是否为ajax请求
     * @param request
     * @return
     */
    private boolean isAjaxRequest(HttpServletRequest request) {
        String requestType = request.getHeader("X-Requested-With");
        if (requestType != null && requestType.equals("XMLHttpRequest")) {
            return true;
        } else {
            return false;
        }
    }


    public String getExceptionMessage() {
        return exceptionMessage;
    }

    public void setExceptionMessage(String exceptionMessage) {
        this.exceptionMessage = exceptionMessage;
    }
}